<template>
  <div>
    <div ref="mapContainer" style="width: 100%; height: 400px;"></div>
  </div>
</template>
<script>
/*及其不建议这样做*/
window._AMapSecurityConfig = {
  securityJsCode: "589d93b773d4b92611fb3dd668127b33",
};
import { onMounted, ref } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useStore } from 'vuex';


export default {
  setup() {
    const store = useStore();
    const mapContainer = ref(null);
    const geolocation = ref(null);

    onMounted(() => {
      AMapLoader.load({
        key: '69927ab15c07363fe79cc54098d046cb', // 你的高德地图开发者密钥
        version: '2.0',
        plugins: ['AMap.Geolocation', 'AMap.Geocoder'], // 加载 Geolocation 和 Geocoder 插件
      })
          .then((AMap) => {
            const map = new AMap.Map(mapContainer.value, {
              zoom: 11,
              center: [116.397428, 39.90923] // 默认位置
            });

            geolocation.value = new AMap.Geolocation({
              enableHighAccuracy: true,
              timeout: 10000,
              buttonPosition: 'RB'
            });
            map.addControl(geolocation.value);

            // 加载完后立即获取定位
            locate(AMap);
          })
          .catch((e) => {
            console.error('AMap Loader 加载失败:', e);
          });
    });

    const locate = (AMap) => {
      if (!geolocation.value) {
        console.error('Geolocation plugin is not loaded');
        return;
      }

      geolocation.value.getCurrentPosition((status, result) => {
        if (status === 'complete' && result.info === 'SUCCESS') {
          const { position } = result;
          console.log("position:", position);
          console.log('经度:', position.lng, '纬度:', position.lat);
          if (result.addressComponent) {
            // 定位成功，获取城市信息
            console.log('城市:', result.addressComponent.city);
          } else {
            // 如果没有城市信息，则使用 Geocoder 服务解析
            reverseGeocode(position, AMap);
          }
        } else {
          console.error('定位失败:', result.message);
        }
      });
    };

    const reverseGeocode = (position, AMap) => {
      const geocoder = new AMap.Geocoder();
      const lnglat = [position.lng, position.lat];

      geocoder.getAddress(lnglat, (status, result) => {
        console.log('Geocoder response:', status, result);
        if (status === 'complete' && result.info === 'OK') {
          // 解析成功，获取城市信息
          const addressComponent = result.regeocode.addressComponent;

          // 存储到vuex中
          let updatedData = {
            city: addressComponent.city || addressComponent.province,
            position: result
          };
          store.commit('updateMapData', updatedData);


          console.log('解析城市:', addressComponent.city || addressComponent.province);
        } else {
          console.error('解析地址失败:', result.message);
        }
      });
    };

    return { mapContainer };
  }
};
</script>


<style>
/* 可以添加一些样式 */
</style>
